package com.test.test.aspect;
/*
 *  成都市深眯科技有限技术公司
 *
 * https://zy.cdshenmi.cn/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

import com.test.test.annotation.LimitClick;
import com.test.test.exception.LimitException;
import com.test.test.utils.IpUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.lang.reflect.Method;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * @author zhuiyi
 * @date 2024/1/15
 */
@Aspect
@Component
public class LimitClickAspect {

    private RedisTemplate<Object, Object> redisTemplate;
    private RedisScript<Long> limitScript;

    @Autowired
    public void setLimitScript(RedisScript<Long> limitScript) {
        this.limitScript = limitScript;
    }

    @Autowired
    public void setRedisTemplate1(RedisTemplate<Object, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Before("@annotation(limitClick)")
    public void doBefore(JoinPoint point, LimitClick limitClick) throws Throwable {
        String key = limitClick.key();
        int time = limitClick.time();
        int count = limitClick.count();

        StringBuffer stringBuffer = new StringBuffer(key);
        // 获取ip地址
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String ipAddr = IpUtils.getIpAddr(attributes.getRequest());
        stringBuffer.append(ipAddr).append("-");
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        Class<?> targetClass = method.getDeclaringClass();
        stringBuffer.append(targetClass.getName()).append("-").append(method.getName());
        String combineKey = stringBuffer.toString();
        List<Object> keys = Collections.singletonList(combineKey);
        try {
            Long number = redisTemplate.execute(limitScript, keys, count, time);
            if (Objects.isNull(number) || number.intValue() > count) {
                throw new LimitException("访问过于频繁，请稍候再试");
            }
        } catch (LimitException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException("服务器限流异常，请稍候再试");
        }
    }

}
